﻿using System;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using NC.Cather;
using NC.Cather.Helper;
using NC.Infrastructure;
using NC.Infrastructure.Data;
using NC.Infrastructure.Domain.Identity;
using NC.Service.Person;
using NC.Service.Target;
using domainEntity = NC.Cather.Target;


namespace NC.Web.Areas.Admin.Controllers
{
    public class TargetController : Controller
    {
        private readonly ITargetService _targetService;
        private readonly IPersonService _personService;
        private readonly IRepository<UrlList> _urlListRepository;
        public TargetController(ITargetService targetService,IPersonService personService,IRepository<UrlList> urlListRepository)
        {
            this._targetService = targetService;
            this._personService = personService;
            this._urlListRepository = urlListRepository;
        }

        // GET: Target/Index
        public ActionResult Index(string search = "", int page = 0, string startTime = "", string endTime = "", int size = 10,int personId=-1)
        {
            //处理Cookie
            if (personId == -1)
                personId = Convert.ToInt32(Session["personId"]);
            else
                Session["personId"] = personId;
            var data = _personService.GetTargets(personId);
            if (!string.IsNullOrEmpty(search))
                data = data.Where(n => n.Id != 0);
            DateTime startTimes, endTimes;
            if (DateTime.TryParse(startTime, out startTimes) && DateTime.TryParse(endTime, out endTimes))
                data = data.Where(n => n.CreatedAt >= startTimes && n.CreatedAt <= endTimes);
            ViewBag.count = data.Count();
            return View(data.OrderByDescending(n => n.CreatedAt).Skip(page * size).Take(size).ToList());
        }

        public ActionResult Details(int id)
        {
            return View();
        }

        // GET: Target/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Target/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult Create(domainEntity entity)
        {
            if (ModelState.IsValid)
            {
                var personId = Convert.ToInt32(Session["personId"]);
                var person = _personService.Get(personId);
                _targetService.Insert(entity,personId);
                _targetService.Commit();
                return RedirectToAction("Index");
            }
            return View(entity);
        }

        // GET: Target/Edit/5
        public ActionResult Edit(int id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            domainEntity Target = _targetService.Get(id);
            if (Target == null)
            {
                return HttpNotFound();
            }

            return View(Target);
        }

        // POST: Target/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult Edit(domainEntity entity)
        {
            if (ModelState.IsValid)
            {
                _targetService.Update(entity);
                _targetService.Commit();
                return RedirectToAction("Index");
            }

            return View(entity);
        }

        // POST: Target/Delete/5
        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            string[] ids = id.Split('|');
            int _id;
            foreach (var item in ids)
            {
                _id = Convert.ToInt32(item);
                var _entity = _targetService.Get(_id);
                _targetService.Delete(_entity);
            }
            _targetService.Commit();
            return Json("", JsonRequestBehavior.AllowGet);
        }

        #region Api
        /// <summary>
        /// 停用此接口
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult StopTarget(int id)
        {
            var target = _targetService.Get(id);
            if (target == null)
                return Json(new { status = 0, msg = "不存在此实体" });
            target.Status = TargetStatus.Stop;
            _targetService.Commit();
            return Json(new { status = 1 });
        }
        /// <summary>
        /// 删除此接口
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DeleteTarget(int id)
        {
            var target = _targetService.Get(id);
            if (target == null)
                return Json(new { status = 0, msg = "不存在此实体" });
            target.Status = TargetStatus.Deleted;
            _targetService.Commit();
            return Json(new { status = 1 });
        }

        /// <summary>
        /// 检查此地址是否有效
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult CheckUrl(string url="")
        {
            string check = CheckHelper.CheckUrlIsValid(url);
            if (!string.IsNullOrEmpty(check))
                return Json(new {status = 0, msg = check});
            return Json(new {status = 1});
        }


        #endregion


        #region UrlList
        public ActionResult AddUrlList(int targetId)
        {
            var urlList = _urlListRepository.Get(n => n.Target.Id == targetId);
            return View(urlList.ToList());
        }

        [HttpPost]
        public ActionResult RemoveUrlList(int id)
        {
            var urlList = _urlListRepository.Get(id);
            _urlListRepository.Delete(urlList);
            _urlListRepository.Commit();
            return Json(new {});
        }

        #endregion


        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
        }
    }
}
